<template>
  <div class="chat-page">
    <div class="chat-header">
      <div class="flex">
        <img
          class="company-logo"
          :src="logoInfo.logoImg"
          v-if="logoInfo.logoEnable == 0 && logoInfo.logoType == 1"
        />
        <svg-icon
          name="defaultLogo"
          width="36px"
          height="36px"
          color="white"
          v-if="logoInfo.logoEnable == 0 && logoInfo.logoType == 0"
        />
        <h1 class="chat-title" v-if="pageData.chatTitle">{{ pageData.chatTitle }}</h1>
      </div>
      <div class="flex">
        <div @click="toggleMute()" style="cursor: pointer">
          <svg-icon
            :name="pageData.muteFlag ? 'mute' : 'unmute'"
            :style="'margin-right: 15px'"
          ></svg-icon>
        </div>
        <div @click="clickClose()" style="cursor: pointer">
          <svg-icon name="close"></svg-icon>
        </div>
      </div>
    </div>
    <div class="chat-body">
      <div class="body-left">
        <div class="notice-area" id="noticeArea" v-if="showNoticeList.length > 0">
          <div class="notice-scroll custom-scrollbar">
            <div
              class="notice-item"
              v-for="(item, index) in showNoticeList"
              :key="index"
              :style="{ marginTop: index == 0 ? '0' : '8px' }"
              @click="chatManager.clickNotice(item)"
            >
              <img src="../../assets/images/notice_icon.webp" class="notice-icon" />
              <span class="notice-title">{{ item.title }}</span>
              <div
                v-if="index == 0 && noticeList.length > 1 && !pageData.expendNotice"
                class="notice-more"
              >
                共&nbsp;{{ noticeList.length }}&nbsp;条
              </div>
            </div>
          </div>
          <div class="notice-fold" v-if="noticeList.length > 1">
            <img
              class="fold-icon"
              src="../../assets/images/up_arrow.webp"
              :class="pageData.expendNotice ? 'rotate-180' : ''"
              @click.stop="chatManager.changeNoticeExpendStatue()"
            />
          </div>
        </div>
        <CardInfo
          v-if="cardInfo"
          :data="cardInfo"
          page-type="pc"
          @send="chatManager.sendParamCardMsg()"
        ></CardInfo>
        <div
          class="message-area"
          :style="chatAutoHeight"
          ref="loadMoreMsg"
          @scroll="chatManager.scrollEvent"
        >
          <ul id="chatcontent">
            <li v-for="(item, index) in chatMsgList" :key="(item.id || item.msgId) as string">
              <div
                class="message-item-area"
                v-if="
                  item.chatPosition == MsgPosition.RIGHT || item.chatPosition == MsgPosition.LEFT
                "
              >
                <!-- 时间 -->
                <span
                  class="message-time system-text left"
                  v-if="item.chatPosition == MsgPosition.LEFT"
                >
                  {{ chatManager.getShowName(item) }}({{ msgTimeDesc(item.createDate) }})
                </span>
                <span class="message-time system-text right" v-else>
                  {{ msgTimeDesc(item.createDate) }}
                </span>
                <div
                  class="message-content"
                  :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                  @mouseover="chatManager.verifyMessageTime(item)"
                >
                  <el-image class="message_item_avator" :src="chatManager.getAvatarUrl(item)">
                    <template #error>
                      <img
                        src="../../assets/images/avatar/agent_avatar.webp"
                        class="message_item_avator"
                      />
                    </template>
                  </el-image>
                  <el-tooltip
                    placement="top"
                    effect="dark"
                    :disabled="!chatManager.enableWithdraw(item) && !chatManager.canCopy(item)"
                  >
                    <template #content>
                      <div class="tooltip-area">
                        <div
                          v-if="chatManager.canCopy(item)"
                          class="tooltip-btn"
                          @click="(e) => chatManager.copy(e, item.content as string)"
                        >
                          <img class="icon" :src="copyIcon" />
                          <div class="text">复制</div>
                        </div>
                        <div
                          class="tooltip-btn"
                          @click="chatManager.withDrawMessage(item.id)"
                          v-if="chatManager.enableWithdraw(item)"
                        >
                          <img class="icon" :src="withdrawIcon" />
                          <div class="text">撤回</div>
                        </div>
                      </div>
                    </template>
                    <RobotMsg
                      v-if="item.messageType == 'robot'"
                      class="content-area agent-text angent-bubble"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      :message="item"
                      :workGroupConfig="workGroupConfig"
                      :transferAgent="requestAgentAgain"
                      :get-answer="sendRobotMessage"
                    ></RobotMsg>
                    <!-- 评价消息 -->
                    <div
                      class="content-area angent-bubble flex-row"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      style="padding: 0px"
                      v-else-if="
                        item.messageType == MessageType.NOTIFICATION_INVITE_RATE ||
                        item.messageType == MessageType.NOTIFICATION_INVITE_RATE_CLOSE
                      "
                    >
                      <RobotRateMsg
                        v-if="item.content === 'robot'"
                        :chatSessionId="item.chatSessionId || ''"
                        @submitRate="chatManager.submitRate"
                        page-type="pc"
                      ></RobotRateMsg>
                      <RateMsg
                        v-else
                        :chatSessionId="item.chatSessionId || ''"
                        @submitRate="chatManager.submitRate"
                        page-type="pc"
                      ></RateMsg>
                    </div>
                    <div
                      class="content-area agent-text angent-bubble left"
                      v-else-if="item.contentType == MessageType.MESSAGE_OPERATION"
                    >
                      {{ item.content }}
                      <span v-if="item.messageType == MessageType.NOTIFICATION_NO_AGENT">
                        您可以选择&nbsp;<span
                          class="message-click-area"
                          @click="chatManager.clickSendOffline"
                          >发送离线消息</span
                        >
                        <span v-if="enableLeaveMessage">
                          &nbsp;或者&nbsp;
                          <span class="message-click-area" @click="chatManager.clickLeaveMessage"
                            >留言</span
                          >
                        </span>
                      </span>

                      <span
                        v-else-if="
                          item.messageType == MessageType.NOTIFICATION_VISITOR_CLOSE ||
                          item.messageType == MessageType.NOTIFICATION_AGENT_CLOSE ||
                          item.messageType == MessageType.NOTIFICATION_AUTO_CLOSE ||
                          item.messageType == MessageType.NOTIFICATION_TRANSFER_AGENT_CLOSE
                        "
                        class="message-click-area"
                        @click="chatManager.requestAgentAgain"
                        >&nbsp;请求客服</span
                      >

                      <span
                        v-else-if="item.messageType == MessageType.MESSAGE_REQUEST_ERROR"
                        class="message-click-area"
                        @click="chatManager.requestAgentAgain"
                        >&nbsp;重新请求</span
                      >
                    </div>
                    <!-- 文字消息 -->
                    <div
                      class="content-area agent-text angent-bubble"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      v-else-if="
                        item.contentType == MessageType.MESSAGE_TEXT ||
                        item.contentType == MessageType.MESSAGE_RICH ||
                        item.contentType == MessageType.MESSAGE_LINK
                      "
                      v-html="
                        item.contentType == MessageType.MESSAGE_RICH
                          ? item.content
                          : emotionData.faceReg(item.content)
                      "
                    ></div>
                    <!-- 图片消息 -->
                    <div
                      class="chat-img-content"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      v-if="item.contentType == MessageType.MESSAGE_IMAGE"
                    >
                      <el-image class="chat-img" :src="item.content" :preview-src-list="[item.content]">
                        <template #placeholder>
                          <div class="image-placeholder"></div>
                        </template>

                        <template #error>
                          <div class="image-placeholder">
                            <img src="../../assets/images/image_error.webp" class="error-icon" />
                          </div>
                        </template>
                      </el-image>
                    </div>

                    <!-- 视频消息 -->
                    <div
                      class="chat-video-message angent-bubble"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      v-else-if="item.messageType == MessageType.MESSAGE_VIDEO"
                    >
                      <video :src="item.content as string" class="chat-video" controls></video>
                    </div>

                    <!-- 音频消息 -->
                    <div
                      class="content-area angent-bubble"
                      style="padding: 0"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      v-else-if="item.messageType == MessageType.MESSAGE_VOICE"
                    >
                      <audio-bar
                        :isPlaying="
                          playingInfo.playingMessageId == item.id &&
                          playingInfo.isPlaying &&
                          playingInfo.playingType == 'audio'
                        "
                        :progress="
                          playingInfo.playingMessageId == item.id ? playingInfo.audioProgress : 0
                        "
                        :duration="Math.ceil(item.fileMessage.length / 1000) || item.duration"
                        :reverse="item.chatPosition == MsgPosition.RIGHT"
                        @toggle-play="() => chatManager.playAudio(item)"
                        @change-progress="handleProgressUpdate"
                      ></audio-bar>
                    </div>

                    <!-- 卡片/商品/订单消息 -->
                    <div
                      class="content-area"
                      style="background: white; padding: 0px"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      v-else-if="
                        item.contentType == MessageType.MESSAGE_CARD ||
                        item.contentType == MessageType.MESSAGE_GOODS ||
                        item.contentType == MessageType.MESSAGE_ORDER
                      "
                    >
                      <CardMsg :item="item" :chatManager="chatManager" page-type="pc"></CardMsg>
                    </div>
                    <!-- 文件消息 -->
                    <div
                      class="content-area angent-bubble flex-row"
                      :class="[item.chatPosition == MsgPosition.LEFT ? 'left' : 'right']"
                      v-else-if="item.contentType == MessageType.MESSAGE_FILE && item.fileMessage"
                    >
                      <a
                        :href="item.content || item.fileMessage.filePath"
                        class="href-area"
                        target="_blank"
                        :download="item.fileMessage.fileName"
                      >
                        <img
                          class="file-icon"
                          :src="
                            getIconByFileTypeOrUrl(
                              item.fileMessage.fileType,
                              item.fileMessage.fileName || item.fileMessage.filePath
                            )
                          "
                        />
                        <div class="file-name agent-text">{{ item.fileMessage.fileName }}</div>
                      </a>
                    </div>
                  </el-tooltip>

                  <img
                    class="failed-icon"
                    src="../../assets/images/send_failed.webp"
                    v-if="item.chatPosition == MsgPosition.RIGHT && item.status == 'failed'"
                    @click="chatManager.reSendMsg(index, item)"
                  />
                </div>
              </div>

              <!-- 中间的系统消息 -->
              <div class="system-msg-area" v-else>
                <span class="message-time system-text">{{
                  dayjs(item.createDate).format('YYYY-MM-DD HH:mm:ss')
                }}</span>

                <!-- 撤回消息提示 -->
                <div
                  class="center-content system-bubble system-bubble-text center-noice"
                  v-if="item.messageType == MessageType.NOTIFICATION_WITHDRAW"
                ></div>

                <div
                  class="center-content system-bubble system-bubble-text center-noice"
                  v-else-if="
                    item.messageType == MessageType.NOTIFICATION_VISITOR_CLOSE ||
                    item.messageType == MessageType.NOTIFICATION_AGENT_CLOSE ||
                    item.messageType == MessageType.NOTIFICATION_AUTO_CLOSE ||
                    item.messageType == MessageType.NOTIFICATION_TRANSFER_AGENT_CLOSE
                  "
                >
                  &nbsp;{{ item.content
                  }}<span class="message-click-area" @click="chatManager.requestAgentAgain"
                    >请求客服</span
                  >
                </div>

                <!-- 队列排队消息提示 -->
                <span
                  class="center-content system-bubble system-bubble-text center-noice"
                  v-else-if="item.messageType == MessageType.NOTIFICATION_QUEUE"
                  >{{ chatManager.getQueueMsg(item.data) }}</span
                >

                <!-- 视频呼叫失败 -->
                <span
                  class="center-content system-bubble system-bubble-text center-noice"
                  style="color: #ff0000"
                  v-else-if="item.messageType == MessageType.NOTIFICATION_VIDEO_CALL_FAIL"
                  >{{ item.content }}</span
                >

                <!-- 其他提示消息 -->
                <span class="center-content system-bubble system-bubble-text center-noice" v-else>{{
                  item.content
                }}</span>
              </div>
            </li>
            <li style="width: 100%; height: 10px"></li>
            <audio
              id="audio"
              ref="audioRef"
              @ended="chatManager.audioOnended"
              @timeupdate="chatManager.audioOnprogress"
            >
              <source :src="playingInfo.voiceUrl" />
            </audio>
          </ul>
        </div>
        <!-- 输入框 顶部，录音等附加的布局 -->
        <div class="chat-attachment-area" id="chatAttachment">
          <record-view
            v-if="pageData.clickRecord"
            @cancelRecorder="cancelRecorder"
            @sendReorder="sendReorder"
            @recodError="recodError"
          >
          </record-view>
        </div>

        <div class="chat-input-area">
          <div class="expansion-bar">
            <div
              :disabled="!enableEmoji"
              class="expansion-item"
              @click="enableEmoji && chatManager.showEmojiPannel()"
              v-clickOutside="chatManager.emotionClickoutside"
            >
              <svg-icon name="emoji" :color="enableEmoji ? '#666666' : '#C7C7C7'"></svg-icon>
              <div class="emoji-panel" id="inputEmotionBox" v-show="pageData.showEmojiPannel">
                <ul>
                  <li
                    v-for="(item, index) in emotionMap"
                    :key="index"
                    @click.stop="chatManager.selectEmotion(item)"
                  >
                    <span
                      :style="{
                        backgroundPositionY: '-' + index * 30 + 'px',
                        backgroundPositionX: -0
                      }"
                      :title="item.meaning"
                    ></span>
                  </li>
                </ul>
              </div>
            </div>
            <div class="expansion-item">
              <input
                type="file"
                accept="video/*,image/*"
                id="imageInput"
                ref="selectImageRef"
                @change="chatManager.selectFile"
                :disabled="!enableSendFile"
              />
              <svg-icon
                name="picture"
                :color="enableSendFile ? '#666666' : '#C7C7C7'"
                @click="clickSelectImage"
              ></svg-icon>
            </div>
            <div class="expansion-item">
              <input
                type="file"
                accept="*/*"
                id="fileInput"
                ref="selectFileRef"
                @change="chatManager.selectFile"
                :disabled="!enableSendFile"
              />
              <svg-icon
                name="file"
                :color="enableSendFile ? '#666666' : '#C7C7C7'"
                @click="clickSelectFile"
              ></svg-icon>
            </div>
            <div class="expansion-item" @click="chatManager.clickRate()">
              <svg-icon name="rate" :color="enableRate ? '#666666' : '#C7C7C7'"></svg-icon>
            </div>
            <div class="expansion-item" @click="clickRecorder()">
              <svg-icon name="record" :color="enableSendFile ? '#666666' : '#C7C7C7'"></svg-icon>
            </div>
            <div class="expansion-item" @click="chatManager.clickVideo()">
              <svg-icon name="video" :color="enableVideo ? '#666666' : '#C7C7C7'"></svg-icon>
            </div>
          </div>
          <div
            name=""
            :contenteditable="enableSend"
            id="inputContent"
            class="inputContent"
            placeholder="请输入消息"
            @paste.prevent="paste"
            @keydown="chatManager.lineFeed"
            @input="chatManager.sendPreviewDebounce"
          ></div>

          <div class="send-area">
            <div class="right" ref="sendRightRef">
              <div class="send-tip">Enter 发送，Ctrl+Enter 换行</div>
              <button
                class="btn-close-chat hollow-button"
                :disabled="!enableCloseChat"
                @click="chatManager.closeChat"
              >
                结束会话
              </button>
              <button
                class="btn-send-message theme-button"
                @click="chatManager.lineFeed({ keyCode: 'button_send' })"
                :disabled="!enableSend"
              >
                发送
              </button>
            </div>
            <div class="ad-area" v-if="pageData.adList.length > 0">
              <img src="@/assets/images/chat_ad_icon.webp" alt="" class="ad-icon" />
              <div class="marquee-container" :style="serverLinkStyle">
                <div class="marquee" ref="marquee">
                  <a
                    class="ad-text"
                    v-for="item in pageData.adList"
                    :key="item.id"
                    :href="openLink(item.url)"
                    target="_blank"
                    >{{ item.name }}</a
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="body-right" :style="barStyle" v-if="channelBarConfig.enable">
        <div class="tab">
          <div
            class="tab-item"
            v-for="(bar, index) in channelBarConfig.barList"
            :key="index"
            @click="changeBarSelect(index)"
          >
            <div class="tab-text" :class="{ select: barSelectIndex == index }">
              {{ bar.tagName }}
            </div>
          </div>
        </div>
        <div style="" class="rich-content-area">
          <div
            class="rich-content ql-editor"
            v-if="channelBarConfig.barList"
            v-html="processRichText(channelBarConfig.barList[barSelectIndex].tagContent)"
          ></div>
        </div>
      </div>
    </div>
  </div>
  <leave-message-dialog
    :input-height="inputHeight"
    :show-dialog="pageData.showLeaveMessageDialog"
    dialog-type="pc"
    :loading="pageData.sendLeaveMessageLoading"
    @closeDialog="pageData.showLeaveMessageDialog = false"
    @sendLeaveMessage="chatManager.sendLeaveMessage"
  />
  <RateDialog
    :input-height="inputHeight"
    page-type="pc"
    :survey-method="1"
    v-if="pageData.showRate"
    @close="pageData.showRate = false"
    ref="rateDialog"
    @submitRate="chatManager.submitRate"
  />
  <NoticeDialog
    :input-height="inputHeight"
    v-model:show-dialog="pageData.showNoticeDialog"
    page-type="pc"
    :notice-info="pageData.noticeInfo"
  >
  </NoticeDialog>
  <VideoDialog
    ref="videoDialogRef"
    :input-height="inputHeight"
    :videoURL="videoURL || ''"
    @close="handleVideoDialogClose"
  ></VideoDialog>
  <RobotRate ref="robotRateRef" @commit="chatManager.submitRate"></RobotRate>
</template>

<script lang="ts" setup>
import copyIcon from '@/assets/images/chat_copy.webp';
import withdrawIcon from '@/assets/images/chat_withdraw.webp';
import AudioBar from '@/components/audio-bar/AudioBar.vue';
import LeaveMessageDialog from '@/components/leave-message-dialog/index.vue';
import NoticeDialog from '@/components/notice-dialog/notice-dialog.vue';
import RateDialog from '@/components/rate-dialog/rate-dialog.vue';
import VideoDialog from '@/components/video-dialog/videoDialog.vue';
import RobotMsg from '@/views/pc/components/RobotMsg.vue';
import RobotRate from '@/views/pc/components/RobotRate.vue';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import RecordView from '../pc/components/record-view.vue';
import RateMsg from './components/rate/RateMsg.vue';
import RobotRateMsg from './components/rate/RobotRateMsg.vue';
import './quill.css';
//表情数据
import emotionData from '@/emoji';
import dayjs from 'dayjs';

// 聊天消息管理，移动/PC 端通用
import { useChatManager, VideoCallStatuType } from '@/hooks/useChatManager';

import { MessageType, MsgPosition } from '@/lib/types';

import { useAppStore } from '@/stores';
import { getIconByFileTypeOrUrl } from '@/utils/fileType';
import { ElMessageBox } from 'element-plus';
import CardInfo from './components/CardInfo.vue';
import CardMsg from './components/CardMsg.vue';
import { useRoute } from 'vue-router';
const route = useRoute();

const inputHeight = route.query.inputHeight as string

const appStore = useAppStore();

const chatManager = useChatManager({ onRequestOpenCameraMic });
const {
  workGroupConfig,
  robotRateRef,
  sendRobotMessage,
  requestAgentAgain,
  pageData,
  chatMsgList,
  noticeList,
  showNoticeList,
  enableCloseChat,
  enableRate,
  enableSend,
  enableSendFile,
  enableEmoji,
  rateDialog,
  enableLeaveMessage,
  loadMoreMsg,
  audioRef,
  playingInfo,
  enableVideo,
  videoDialogRef,
  videoCallStatus,
  videoURL,
  logoInfo,
  baseURL,
  msgTimeDesc,
  cardInfo,
  sendParamCardMsg,
  sendCardMsg
} = chatManager;

window.sendCardMsg = sendCardMsg;

//表情包
let emotionMap = ref(emotionData.expressionJson);

// 历史消息图片，左右切换消息
// const historyImageList = ref<string[]>([])

// watch(
//   () => chatMsgList.value.length,() => {
//      historyImageList.value = []
//      chatMsgList.value.filter(item =>{
//       if(item.contentType == 'image') {
//         historyImageList.value.push(item.content)
//       }
//     }) as unknown as string[]    
//   }
// )

onMounted(() => {
  chatManager.checkRoute();
  // console.log(chatManager, 'sss');
  let isMute = localStorage.getItem('isMute');
  chatManager.toggleMute(isMute == 'true');
  window.addEventListener('resize', updateViewportWidth);
  if (sendRightRef.value) {
    sendRightWidth.value = sendRightRef.value.offsetWidth;
  }
});

// 系统通知索引
const barSelectIndex = ref(0);

//pc侧边栏配置
const channelBarConfig = computed(() => {
  let channelBar = pageData.infoBarConfig;
  let tags = channelBar.tags;
  if (!tags || tags.length <= 0) {
    return {
      enable: false
    };
  }

  let barList = [];
  for (let i = 0; i < tags.length; i++) {
    const tag = tags[i];
    // TODO: 暂时不支持一个标签页内多个content功能，后端数据已支持
    if (tag.name && tag.contents[0].content) {
      barList.push({
        tagName: tag.name,
        tagContent: tag.contents[0].content
      });
    }
  }
  if (barList.length == 0) {
    return {
      enable: false
    };
  }
  let setWidth = Number(channelBar.width);
  let width = isNaN(setWidth) ? 200 : setWidth;
  return {
    enable: true,
    barList,
    width
  };
});

function processRichText(text: string) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(text, 'text/html');
  const images = doc.querySelectorAll('img');
  if (!images || images.length == 0) {
    return text;
  }

  images.forEach((img) => {
    img.src = `${baseURL.value}/sys/oss/download?token=${appStore.userToken}&url=${decodeURIComponent(img.src)}`; // 创建一个URL对象
  });

  const serializer = new XMLSerializer();
  return serializer.serializeToString(doc.body);
}

function changeBarSelect(index: number) {
  if (index != barSelectIndex.value) {
    barSelectIndex.value = index;
  }
}
// 取消录音
function cancelRecorder() {
  pageData.clickRecord = false;
  nextTick(() => {
    countChatHeight();
  });
}
// 发送录音
function sendReorder(recordResult: any) {
  pageData.clickRecord = false;
  chatManager.sendVoice(recordResult);
  chatMsgList.value[chatMsgList.value.length - 1].duration = recordResult.duration;

  // voiceDuration.value = recordResult.duration
  nextTick(() => {
    countChatHeight();
  });
}

//取消录音
function recodError() {
  pageData.clickRecord = false;
  nextTick(() => {
    countChatHeight();
  });
}

//点击开始录音
function clickRecorder() {
  console.log(enableSendFile.value, 'ss');
  if (enableSendFile.value) {
    pageData.clickRecord = true;
    nextTick(() => {
      countChatHeight();
    });
  }
}

const handleProgressUpdate = (newValue: number) => {
  console.log('Parent received new progress:', newValue);
  playingInfo.audioProgress = newValue;
};
/**
 * 聊天消息高度
 */
const chatAutoHeight = ref({ height: 'calc(100% - 170px)' });

/**
 * 动态计算高度
 */
function countChatHeight() {
  const chatPreElement = document.getElementById('chatAttachment');
  const noticeElement = document.getElementById('noticeArea');
  let noticeHeight = 0;
  if (noticeElement) {
    noticeHeight = noticeElement.clientHeight;
  }
  let chatPreHeight = 0;
  if (chatPreElement) {
    chatPreHeight = chatPreElement.clientHeight;
  }
  chatAutoHeight.value = { height: `calc(100% - 170px - ${noticeHeight + chatPreHeight}px)` };
  chatManager.chatcontentToBottom();
}

chatManager.setCustomCountHeight(countChatHeight);

function openLink(url: string) {
  if (url) {
    return url.startsWith('http') ? url : `https://${url}`;
  }
  return 'javascript:void(0)';
}

function clickClose() {
  chatManager.closeChat();
}
function toggleMute() {
  chatManager.toggleMute(!pageData.muteFlag);
}

onUnmounted(() => {
  window.removeEventListener('resize', updateViewportWidth);
});

//视口宽度
const viewportWidth = ref(window.innerWidth);

const updateViewportWidth = () => {
  viewportWidth.value = window.innerWidth;
};

const barStyle = computed(() => {
  if (!channelBarConfig.value.enable) {
    return {};
  }
  let realWidth = Math.min(viewportWidth.value * 0.34, channelBarConfig.value.width || 0);
  return { width: realWidth + 'px' };
});

const sendRightRef = ref<HTMLElement | null>(null);
const sendRightWidth = ref(0);

//服务链接样式
const serverLinkStyle = computed(() => {
  if (!channelBarConfig.value.enable) {
    return { maxWidth: `${viewportWidth.value - sendRightWidth.value - 38}px` };
  } else {
    let realWidth = Math.min(viewportWidth.value * 0.34, channelBarConfig.value.width || 0);
    return { maxWidth: `${viewportWidth.value - sendRightWidth.value - realWidth - 38}px` };
  }
});

watch(
  () => pageData.adList,
  () => {
    nextTick(() => {
      checkAndClone();
    });
  },
  { deep: true }
);
const marquee = ref(null);
// 判断是否需要克隆内容并触发滚动
const checkAndClone = () => {
  const marqueeElement: any = marquee.value;
  if (!marqueeElement) return;
  const marqueeContainerElement = marqueeElement.parentNode;

  // 获取父容器和内部内容的宽度
  const marqueeContainerWidth = marqueeContainerElement.offsetWidth;
  const marqueeWidth = marqueeElement.scrollWidth;
  // 如果内部内容的宽度大于容器宽度，才进行克隆和滚动
  if (marqueeWidth > marqueeContainerWidth) {
    marqueeElement.innerHTML += marqueeElement.innerHTML; // 克隆一次内容
    // 添加类以启动动画
    marqueeElement.classList.add('marquee-scrolling');
  }
};
function paste(event: any) {
  chatManager.pasteEvent(event);
}

const selectImageRef = ref<HTMLInputElement | null>(null);
function clickSelectImage() {
  if (enableSendFile.value && selectImageRef.value) {
    selectImageRef.value.click();
  }
}
const selectFileRef = ref<HTMLInputElement | null>(null);
function clickSelectFile() {
  if (enableSendFile.value && selectFileRef.value) {
    selectFileRef.value.click();
  }
}

/**
 * 视频窗口关闭处理，如果视频还在通话中改为默认状态
 */
function handleVideoDialogClose() {
  const isTalking =
    videoCallStatus.value === VideoCallStatuType.Requesting ||
    videoCallStatus.value === VideoCallStatuType.Waiting ||
    videoCallStatus.value === VideoCallStatuType.Talking;
  if (isTalking) {
    videoCallStatus.value = VideoCallStatuType.Default;
  }
}

/**
 * 开启/禁用媒体设备
 *
 * @param trackSource 1 摄像头 2 麦克风 3 屏幕共享
 * @param enable 是否禁用
 */
function onRequestOpenCameraMic(soucreType: number, enable: boolean) {
  const sourceName = soucreType === 1 ? '摄像头' : '麦克风';
  ElMessageBox.confirm(`客服请求你开启${sourceName}`, `开启${sourceName}`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true
  })
    .then(() => {
      videoDialogRef.value.openCameraMic(soucreType, enable);
    })
    .catch(() => {});
}

function handleSendTest() {
  window.sendCardMsg({
    href: 'https://moonvy.com/project/bd8064b8-4009-4d2c-ac6c-9ba9d615a7a5/23f99fc4-7eec-45f5-91ef-2d847eca1aff/34f5c315-d4aa-4a11-9458-e3d88f4a2996',
    pic: 'https://static.oschina.net/uploads/cooperation/blog_detail_right_sidebar_1_VzZhA.png',
    title: '测试',
    describe: '',
    number: '123',
    date: '2025-03-31 19:06:06',
    type: 'card'
  });
}
</script>
<style lang="scss" scoped>
 $input-height: v-bind(inputHeight);
 @import '@/styles/setInputHeight.scss';
.chat-page {
  width: 100vw;
  height: 100vh;
  min-width: 600px;
  display: flex;
  flex-direction: column;
}

.chat-header {
  width: 100%;
  height: 45px;
  display: flex;
  justify-content: space-between;
  background-color: var(--color-title-bg);
  align-items: center;
  padding: 0 12px;

  .company-logo {
    width: auto;
    height: 32px;
    object-fit: contain;
  }

  .flex {
    display: flex;
    align-items: center;
  }

  .chat-title {
    color: var(--color-title-text);
    font-weight: 700;
    margin-left: 12px;
    font-size: 16px;
  }
}

.chat-body {
  height: calc(100vh - 45px);
  display: flex;
  flex-direction: row;

  .body-left {
    flex: 1;
    height: 100%;
    border-right: 1px solid #dadada;
    display: flex;
    flex-direction: column;

    .notice-area {
      background-color: #ececec;
      width: 100%;
      height: fit-content;
      display: flex;
      flex-direction: column;
      padding: 8px;
      box-sizing: border-box;
      border-radius: 0px 0px 8px 8px;
      z-index: 99;
      box-shadow: -2px 2px 10px -1px rgba($color: #000000, $alpha: 0.12);

      .notice-scroll {
        overflow-y: auto;
        max-height: 118px;
      }

      .notice-item {
        width: 100%;
        height: 34px;
        border-radius: 4px;
        padding: 0px 8px;
        box-sizing: border-box;
        background-color: #ffffff;
        display: flex;
        justify-content: baseline;
        align-items: center;
        cursor: pointer;

        .notice-icon {
          width: 16px;
          height: 16px;
          flex-shrink: 0;
        }

        .notice-title {
          margin-left: 12px;
          flex-grow: 1;
          color: var(--color-text-2);
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 14px;
          line-height: 22px;
          height: 22px;
        }

        .notice-more {
          margin-left: 12px;
          flex-shrink: 0;
          color: var(--color-text-2);
          font-size: 14px;
          line-height: 22px;
          height: 22px;
        }
      }

      .notice-fold {
        width: 42px;
        margin-top: 8px;
        height: fit-content;
        display: inline-flex;
        flex-shrink: 0;
        border-radius: 8px;
        align-self: center;
        background: #dadada;

        .fold-icon {
          width: 16px;
          height: 16px;
          margin: auto;
          cursor: pointer;
          transition: transform 0.2s ease-in-out;
        }

        .rotate-180 {
          transform: rotate(180deg);
        }
      }
    }

    .message-area {
      width: 100%;
      box-sizing: border-box;
      background-color: var(--color-chat-bg);
      overflow-y: auto;
    }

    .chat-attachment-area {
      width: 100%;
    }

    .chat-input-area {
      height: 170px;
      box-sizing: border-box;
      border-top: 1px solid #dadada;
      display: flex;
      flex-direction: column;

      .expansion-bar {
        width: 100%;
        height: 30px;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        padding: 0 10px;

        .expansion-item {
          width: 20px;
          height: 20px;
          margin-right: 16px;
          cursor: pointer;
          position: relative;

          input[type='file'] {
            position: absolute;
            top: 0;
            left: 0;
            width: 20px;
            height: 20px;
            opacity: 0;
            display: block;
            caret-color: transparent;
            cursor: pointer;
            pointer-events: none;
          }
        }
      }
    }

    .inputContent {
      outline: none;
      box-sizing: border-box;
      padding: 5px;
      background: #ffffff;
      overflow-y: auto;
      font-size: 13px;
      flex: 1;
      caret-color: #333333;

      line-height: 1.5;
      /* 调整行高以适应不同大小的表情 */
      word-break: break-word;
      /* 防止长单词或URL破坏布局 */
    }

    .send-area {
      display: flex;
      height: 40px;
      width: 100%;
      box-sizing: border-box;
      padding-right: 20px;
      padding-left: 10px;
      height: 40px;
      align-items: center;
      flex-direction: row-reverse;

      .right {
        display: flex;
        align-items: center;
      }

      .btn-send-message {
        width: 56px;
        height: 32px;
        border: none;
        flex-shrink: 0;
        font-size: 14px;
      }

      .btn-close-chat {
        width: 84px;
        height: 32px;
        flex-shrink: 0;
        margin-right: 8px;
        font-size: 14px;
      }

      .send-tip {
        width: wrap;
        margin-right: 8px;
        color: #999999;
        font-weight: 400;
        font-size: 12px;
      }

      .ad-area {
        flex: 1;
        align-items: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: flex;

        .ad-icon {
          width: 14px;
          height: 14px;
        }
      }
    }
  }

  .marquee-container {
    overflow: hidden;
    white-space: nowrap;
    margin: 0 12px;
    box-sizing: border-box;
  }

  /* 内层容器：控制滚动动画 */
  .marquee {
    display: flex;
    width: fit-content;
    box-sizing: border-box;
    animation-play-state: running;
    /* 默认状态为动画运行 */

    a {
      display: block;
      height: 20px;
      width: fit-content;
      line-height: 20px;
      white-space: nowrap;
      color: var(--color-system-text);
      font-size: 12px;
      flex-shrink: 0;
      box-sizing: border-box;
      padding: 0 12px;
      text-decoration: none;
      transition: color 0.3s ease;
      /* 添加过渡效果，使颜色变化更顺滑 */
    }
  }

  /* 悬停时链接颜色变化 */
  .marquee a:hover {
    color: var(--color-main-theme);
  }

  .marquee:hover {
    animation-play-state: paused;
  }

  /* 定义滚动的关键帧动画 */
  @keyframes marquee-scroll {
    0% {
      transform: translateX(0);
    }

    100% {
      transform: translateX(-50%);
      /* 滚动半个长度 */
    }
  }

  /* 内层容器：控制滚动动画 */
  .marquee-scrolling {
    animation: marquee-scroll 30s linear infinite;
  }

  .body-right {
    height: 100%;
    display: flex;
    flex-direction: column;

    .tab {
      max-width: 100%;
      height: 42px;
      display: flex;
      justify-content: space-evenly;
      box-sizing: border-box;
      border-bottom: 1px solid #dadada;

      .tab-item {
        max-width: 33%;
        flex: 1;
        flex-shrink: 0;
        cursor: pointer;
      }

      .tab-text {
        text-align: center;
        line-height: 42px;
        height: 42px;
        font-size: 13px;
        margin: 0 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        &.select {
          border-bottom: 2px solid var(--color-main-theme);
          color: var(--color-main-theme);
        }
      }
    }
  }
}

.rich-content-area {
  box-sizing: border-box;
  overflow: auto;

  .rich-content {
    font-size: 13px;
    line-height: 22px;

    img {
      width: 100px !important;
    }
  }
}

.emoji-panel {
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-bottom: 0;
  border-left: 0;
  height: 160px;
  width: 400px;
  overflow-y: auto;
  position: absolute;
  top: -174px;
  left: -45px;
}

.emoji-panel ul {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  list-style: none;
}

.emoji-panel li span {
  width: 30px;
  height: 30px;
  background: url(../../assets/images/appkefu_sprites.png);
  background-size: 30px auto;
  display: block;
}

.message-item-area {
  margin-left: 12px;
  margin-right: 12px;
  margin-top: 16px;
  display: flex;
  flex-direction: column;

  .message-content {
    margin-top: 6px;
    font-size: 13px;
    display: flex;
    line-height: 22px;

    &.left {
      flex-direction: row;
      justify-content: flex-start;
    }

    &.right {
      flex-direction: row-reverse;
    }

    .failed-icon {
      width: 20px;
      height: 20px;
      margin-right: 8px;
      align-self: center;
    }

    .message_item_avator {
      width: 30px;
      height: 30px;
      border-radius: 15px;
      background-color: var(--color-main-theme);
      display: inline-block;
    }

    .content-area {
      max-width: 80%;
      line-height: 22px;
      flex-shrink: 0;
      padding: 8px 12px;
      font-size: 13px;
      box-sizing: border-box;
      letter-spacing: -1.5%;

      &.left {
        margin-left: 12px;
        border-radius: 0px 8px 8px 8px;
      }

      &.right {
        margin-right: 12px;
        border-radius: 8px 0px 8px 8px;
      }

      &.flex-column {
        display: flex;
        flex-direction: column;
      }

      &.flex-row {
        display: flex;
        flex-direction: row;
      }
    }

    .file-icon {
      width: 32px;
      height: 32px;
      align-self: center;
    }

    .file-name {
      align-self: center;
      margin-left: 12px;
      max-height: 42px;
      color: #333333;
      font-family: PingFang SC;
      font-size: 13px;
      line-height: 21px;
      word-break: break-all;
      overflow-wrap: break-word;
    }

    .chat-img-content {
      max-width: 25%;
      min-width: 140px;

      &.left {
        margin-left: 12px;
      }

      &.right {
        margin-right: 12px;
      }
    }

    .chat-video-message {
      max-width: 22%;
      min-width: 140px;
      position: relative;
      object-fit: contain;

      &.left {
        margin-left: 12px;
      }

      &.right {
        margin-right: 12px;
      }
    }
  }
}

.chat-img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;

  .image-placeholder {
    width: 140px;
    height: 90px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f1f1f1;
    border-radius: 8px;
  }

  .error-icon {
    width: 30px;
    height: 30px;
  }

  &.fixed-height {
    height: 90px;
  }
}

.chat-video {
  max-width: 100%;
  height: 100%;
  border-radius: 8px;
}

.video-play {
  width: 40px;
  height: 40px;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  position: absolute;
}

.video-duration {
  position: absolute;
  bottom: 4%;
  right: 8px;
  line-height: 22px;
  font-size: 14px;
  height: 22px;
  color: white;
}

.message-click-area {
  color: var(--color-main-theme);
  cursor: pointer;
}

.message-time {
  font-size: 12px;
  height: 18px;
  color: var(--color-system-text);
  font-size: 12px;
  line-height: 18px;

  &.left {
    margin-left: 42px;
    align-self: flex-start;
  }

  &.right {
    margin-right: 42px;
    align-self: flex-end;
  }
}

.system-msg-area {
  margin-top: 16px;
  margin-left: 16px;
  margin-right: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;

  .center-content {
    margin-top: 6px;
    font-size: 13px;
    display: flex;
    line-height: 22px;
    padding: 0 12px;
    border-radius: 4px;
  }
}

.tooltip-area {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 4px;

  .tooltip-btn {
    cursor: pointer;
    display: flex;
    flex-direction: row;
    align-items: center;

    .icon {
      width: 22px;
      height: 22px;
    }

    .text {
      height: 22px;
      color: #ffffff;
      margin-left: 6px;
      font-size: 14px;
      line-height: 22px;
      letter-spacing: -0.5%;
    }
  }
}

.goods-href {
  display: flex;
  flex-direction: column;

  .card-title {
    width: 100%;
    color: #333333;
    font-weight: 500;
    font-size: 14px;
    line-height: 22px;
  }

  .card-content {
    width: 100%;
    display: flex;
    margin-top: 8px;

    .goods-price {
      line-height: 20px;
      color: #666666;
      font-size: 12px;
    }

    .goods-datainfo {
      color: #666666;
      font-size: 12px;
      line-height: 18px;
      margin-left: 12px;
      letter-spacing: -1%;
    }
  }

  img {
    display: block;
    flex-shrink: 0;
    align-items: top;
    width: 56px;
    height: 56px;
  }
}

.href-area {
  display: flex;
  cursor: pointer;
}

.href-area:hover,
.href-area:active {
  background-color: transparent;
}
</style>
